<template>
  <div class="login">
    <el-form ref="form" :model="form" :rules="rules" class="login-form">
      <div class="login_title">
        <h2>后台管理系统</h2>
      </div>
      <el-form-item prop="username">
        <el-input
          placeholder="请输入登录账号"
          prefix-icon="el-icon-user"
          v-model="form.username"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入密码"
          prefix-icon="el-icon-lock"
          type="password"
          v-model="form.password"
          auto-complete="off"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" :loading="isLoginLoading" type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import { login } from '@/api/auth/user'

export default Vue.extend({
  name: 'LoginIndex',
  data () {
    return {
      isLoginLoading: false,
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      try {
        await (this.$refs.form as Form).validate()
        this.isLoginLoading = true

        const { data } = await login(this.form)
        if (data.code !== 200) {
          this.isLoginLoading = false
          return this.$message.error(data.message)
        }
        this.$message.success('登录成功')
        this.$store.commit('setUser', data.data)
        this.$router.push(this.$route.query.redirect as string || '/')
      } catch (err) {
        console.log('登录失败', err)
      }

      this.isLoginLoading = false
    }
  }
})
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('../../assets/images/loginbg.jpg') center center no-repeat;
  .login-form{
    width: 300px;
    background: #ffffff;
    padding: 1% 3%;
    border-radius: 10px;
    opacity: 0.95;
    color: #111111;
  }
  .login_title{
    color: #111111;
    text-align: center;
    margin-bottom: 10%;
  }
  .login-btn{
    width: 100%;
  }
}
</style>
